﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using BbsbWebService.Classes;
using BbsbWebService.Enums;
using BbsbWebService.Tasks;
using BbsbWebService.Repositories;

namespace BbsbWebService
{
    /// <summary>
    /// Interaction logic for AddGroupWindow.xaml
    /// </summary>
    public partial class TaskDetails : Window
    {
        #region Private Members

        private Guid _initialTaskId = Guid.Empty;

        private static List<int> Magnitudes
        {
            get
            {
                List<int> retVal = new List<int>();
                for (int i = 1; i < 25; i++)
                {
                    retVal.Add(i);
                }
                return retVal;
            }
        }

        #endregion

        public TaskDetails(BaseTask task)
        {
            InitialiseComponentValues();
            _initialTaskId = task.Id;
            RefreshPanels();
            Task = task;
            nameTxt.Text = task.Name;
            InitTaskValues();
        }

        public TaskDetails()
        {
            InitialiseComponentValues();
            Task = new OneOffTask();
            RefreshPanels();
            isActive.IsChecked = true;
        }

        public BaseTask Task { get; set; }

        private void InitialiseComponentValues()
        {
            InitializeComponent();

            // set recurring drop down and magnitude
            recurringCbo.ItemsSource = Enum.GetNames(typeof(RecurringFrequency));
            recurringCbo.SelectedIndex = 0;

            magnitudeCbo.ItemsSource = Magnitudes;
            magnitudeCbo.SelectedIndex = 0;

            allItems.ItemsSource = RepositoryInstances.ItemRepository.Items;
            allItems.Items.Refresh();
            allGroups.ItemsSource = RepositoryInstances.GroupRepository.Items;
            allGroups.Items.Refresh();

            powerCbo.ItemsSource = Enum.GetNames(typeof(PowerOption));
            powerCbo.SelectedIndex = 0;

            oneOffDate.DisplayDateStart = DateTime.Now;
        }

        private void InitTaskValues()
        {
            powerCbo.SelectedItem = Task.PowerOption;
            if (Task.NextAlarm.HasValue)
            {
                timePicker.Value = Task.NextAlarm.Value;
            }

            isActive.IsChecked = !Task.Disabled;

            if (Task.Item is Group)
            {
                allGroups.SelectedItem = Task.Item;
            }
            else if (Task.Item is ControllableItem)
            {
                allItems.SelectedItem = Task.Item;
            }

            if (Task is OneOffTask)
            {
                // One Off task..
                oneOffDate.SelectedDate = Task.NextAlarm;
                oneOffTaskBtn.IsChecked = true;
            }
            else if (Task is ScheduledTask)
            {
                // Scheduled task..
                mondayChb.IsChecked = IsDayChecked(WeekDay.Monday);
                tuesdayChb.IsChecked = IsDayChecked(WeekDay.Tuesday);
                wednesdayChb.IsChecked = IsDayChecked(WeekDay.Wednesday);
                thursdayChb.IsChecked = IsDayChecked(WeekDay.Thursday);
                fridayChb.IsChecked = IsDayChecked(WeekDay.Friday);
                saturdayChb.IsChecked = IsDayChecked(WeekDay.Saturday);
                sundayChb.IsChecked = IsDayChecked(WeekDay.Sunday);
                scheduledTaskBtn.IsChecked = true;
            }
            else if (Task is RecurringTask)
            {
                // Recurring Task
                magnitudeCbo.SelectedItem = ((RecurringTask)Task).Magnitude;
                recurringCbo.SelectedItem = ((RecurringTask)Task).Frequency.ToString();
                recurringTaskBtn.IsChecked = true;
            }
        }

        private void RefreshPanels()
        {
            if (Task is OneOffTask)
            {
                oneOffTaskBtn.IsChecked = true;
                oneOffGrid.Visibility = Visibility.Visible;
                recurringGrid.Visibility = Visibility.Hidden;
                scheduledGrid.Visibility = Visibility.Hidden;

            }
            else if (Task is RecurringTask)
            {
                recurringTaskBtn.IsChecked = true;
                oneOffGrid.Visibility = Visibility.Hidden;
                recurringGrid.Visibility = Visibility.Visible;
                scheduledGrid.Visibility = Visibility.Hidden;
            }
            else if (Task is ScheduledTask)
            {
                scheduledTaskBtn.IsChecked = true;
                oneOffGrid.Visibility = Visibility.Hidden;
                recurringGrid.Visibility = Visibility.Hidden;
                scheduledGrid.Visibility = Visibility.Visible;
            }
        }

        private bool IsDayChecked(WeekDay weekDay)
        {
            ScheduledTask task = Task as ScheduledTask;
            bool retVal = false;

            if (task != null)
            {
                retVal = (task.Days & weekDay) == weekDay;
            }

            return retVal;
        }

        #region Events

        private void saveBtn_Click(object sender, RoutedEventArgs e)
        {
            BaseItem selectedItem = null;

            if (allItems.SelectedItem != null)
                selectedItem = allItems.SelectedItem as BaseItem;
            else if (allGroups.SelectedItem != null)
                selectedItem = allGroups.SelectedItem as BaseItem;

            if (selectedItem != null)
            {
                if (_initialTaskId == Guid.Empty)
                {
                    _initialTaskId = Guid.NewGuid();
                }

                string name = nameTxt.Text;

                DateTime now = DateTime.Now;
                TimeSpan time = timePicker.Value.TimeOfDay;

                // Do other tasky savey stuff
                if (Task is RecurringTask)
                {
                    RecurringFrequency frequency = recurringCbo.SelectedItem.ToString().ToEnum<RecurringFrequency>();

                    DateTime nextAlarm = new DateTime(now.Year, now.Month, now.Day, time.Hours, time.Minutes, time.Seconds);
                    int magnitude = (int)magnitudeCbo.SelectedItem;
                    Task = new RecurringTask(nextAlarm, frequency, magnitude);
                }
                else if (Task is OneOffTask)
                {
                    if (oneOffDate.SelectedDate.HasValue)
                    {
                        DateTime dateTime = oneOffDate.SelectedDate.Value;
                        dateTime = dateTime.Add(time);
                        Task = new OneOffTask(dateTime);
                    }
                }
                else if (Task is ScheduledTask)
                {
                    WeekDay days = WeekDay.None;

                    if (mondayChb.IsChecked == true)
                    {
                        days |= WeekDay.Monday;
                    }
                    if (tuesdayChb.IsChecked == true)
                    {
                        days |= WeekDay.Tuesday;
                    }
                    if (wednesdayChb.IsChecked == true)
                    {
                        days |= WeekDay.Wednesday;
                    }
                    if (thursdayChb.IsChecked == true)
                    {
                        days |= WeekDay.Thursday;
                    }
                    if (fridayChb.IsChecked == true)
                    {
                        days |= WeekDay.Friday;
                    }
                    if (saturdayChb.IsChecked == true)
                    {
                        days |= WeekDay.Saturday;
                    }
                    if (sundayChb.IsChecked == true)
                    {
                        days |= WeekDay.Sunday;
                    }

                    Task = new ScheduledTask(days, new DateTime(now.Year, now.Month, now.Day - 1, time.Hours, time.Minutes, time.Seconds));
                }

                Task.Name = nameTxt.Text;
                Task.Id = _initialTaskId;
                Task.Item = selectedItem;
                Task.PowerOption = (PowerOption)powerCbo.SelectedIndex;
                Task.Disabled = isActive.IsChecked != true;
            }

            var state = Task.ValidationState;
            if (state.IsValid)
            {
                this.DialogResult = true;
                this.Close();
            }
            else
            {
                MessageBox.Show(state.ToString());
            }
        }

        private void cancelBtn_Click(object sender, RoutedEventArgs e)
        {
            Task = null;
            this.Close();
        }

        private void oneOffTaskBtn_Checked(object sender, RoutedEventArgs e)
        {
            Task = new OneOffTask();
            RefreshPanels();
        }

        private void recurringTaskBtn_Checked(object sender, RoutedEventArgs e)
        {
            Task = new RecurringTask();
            RefreshPanels();
        }

        private void scheduledTaskBtn_Checked(object sender, RoutedEventArgs e)
        {
            Task = new ScheduledTask();
            RefreshPanels();
        }

        private void allItems_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (allItems.SelectedItem != null)
            {
                // we have an item selected, so clear any groups selected...
                allGroups.SelectedIndex = -1;
            }
        }

        private void allGroups_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (allGroups.SelectedItem != null)
            {
                // we have a group selected, so clear any items selected...
                allItems.SelectedIndex = -1;
            }
        }

        #endregion
    }
}
